#!/bin/bash
# vim: fdm=marker fmr=[[[,]]] cms=\ #%s

get_from_nginx_conf()
{ #[[[
    local key=$1

    awk '$1 ~ /'$key'/ { gsub(";$","",$2); print $2; exit; }' $SERVER_DIR/conf/nginx.conf
} #]]]

get_from_php_ini()
{ #[[[
    local key=$1

    awk '
/^ *'$key' *=/ {
    gsub("^ *'$key' *=", "");
    gsub("^ *", "");
    gsub("^\"", "");
    gsub(" *$", "");
    gsub("\"$", "");
    print;
    exit;
}' $SERVER_DIR/conf/php.ini
} #]]]

usage()
{ #[[[
    echo "Usage: svrctl start | stop | status"
} #]]]

running()
{ #[[[
    local proc=$1
    local pid=$(ps -ef|grep -v grep|awk '$8~/'$proc'/ { print $2 }')
    if [[ -n $pid ]]
    then
        return 1
    fi
} #]]]

command()
{ #[[[
    case $1 in
    start)
        running nginx
        if (( $? == 1 ))
        then
            echo "nginx is running, stop first, quit..."
            return 1
        fi
        running php-cgi
        if (( $? == 1 ))
        then
            echo "php-cgi is running, stop first, quit..."
            return 1
        fi

        local user=$(get_from_nginx_conf user)
        export PHP_FCGI_CHILDREN=$(get_from_php_ini php_fcgi_children)
        export PHP_FCGI_MAX_REQUESTS=$(get_from_php_ini php_fcgi_max_requests)

        cd $SERVER_DIR/sbin
        ./nginx
        sleep 1
        running nginx
        if (( $? == 0 ))
        then
            echo "nginx start fail, check..."
            return 1
        fi

        cd $SERVER_DIR/php/bin
        su $user -c "./php-cgi -b ../../logs/php-cgi.sock &"
        sleep 2
        running php-cgi
        if (( $? == 0 ))
        then
            echo "php-cgi start fail, check..."
            return 1
        fi

        echo "nginx+php-cgi start succeed"
        ;;

    stop)
        killall nginx
        killall php-cgi
        sleep 2
        running nginx
        if (( $? != 0 ))
        then
            echo "nginx stop fail, check..."
        else
            echo "nginx stop succeed"
        fi
        running php-cgi
        if (( $? != 0 ))
        then
            echo "php-cgi stop fail, check..."
        else
            echo "php-cgi stop succeed"
        fi
        ;;

    status)
        ps -ef|grep -v grep|awk '$8~/nginx/ { print }'
        ps -ef|grep -v grep|awk '$8~/php-cgi/ { print }'
        ;;
    *)
        usage
        ;;
    esac
} #]]]

interact()
{ #[[[
    local option
    read -p "\
Options:
    1) start
    2) stop

    s) status
Choose: " option
    case $option in
    1) command start ;;
    2) command stop ;;
    s) command status ;;
    *) command ? ;;
    esac
} #]]]

main()
{ #[[[
    local bin_dir=$(dirname $0)
    if [[ ${bin_dir:0:1} != '/' ]]
    then
        bin_dir=$PWD/$bin_dir
    fi
    SERVER_DIR=$bin_dir/..

    if (( $# == 0 ))
    then
        interact
    else
        command "$1"
    fi
} #]]]

SERVER_DIR=

main $@
exit $?
